package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.RecommendUser;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@DubboService
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //根据touserId查询,缘分值最高的一项推荐数据
    public RecommendUser findWithMaxScore(Long toUserId) {
        //1、构建Criteria
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2、根据Criteria构建Query
        Query query = Query.query(criteria)
                            .with(Sort.by(Sort.Order.desc("score"))) //排序
                            .limit(1);
        //3、调用find或者findOne查询
        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    //根据toUserId分页查询推荐数据
    public List<RecommendUser> findRecommentUserList(Long toUserId, Integer page, Integer pagesize) {
        //1、构建Criteria
        Criteria criteria = Criteria.where("toUserId").is(toUserId);
        //2、根据Criteria构建Query
        Query query = Query.query(criteria);
        //3、查询总数
        long count = mongoTemplate.count(query, RecommendUser.class);
        System.out.println("总条数="+count);
        //4、向query对象中设置分页参数
        query.with(Sort.by(Sort.Order.desc("score")))
                .limit(pagesize)
                .skip((page-1) * pagesize);
        //5、调用MongoTemplate的find方法，查询数据列表
        return mongoTemplate.find(query,RecommendUser.class);
    }

    //根据用户id和toUserId查询推荐数据
    public RecommendUser queryByUserId(Long userId, Long toUserId) {
        //select * from tab where userId=? AND toUserId=?
        //1、构建Criteria并设置查询条件
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("toUserId").is(toUserId);
        //2、通过Criteria创建Query
        Query query = Query.query(criteria);
        //3、调用mongoTemplate的find或者findOne查询
        RecommendUser user = mongoTemplate.findOne(query, RecommendUser.class);
        if(user == null) { //刚刚注册的新用户,默认数据
            user = new RecommendUser();
            user.setUserId(userId);
            user.setToUserId(toUserId);
            user.setScore(95d);
        }
        return user;
    }
}
